﻿using EventModel;
using GreenPipes;
using MassTransit;
using MassTransit.ExtensionsDependencyInjectionIntegration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using System;

namespace ExamEventBus
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //注入数据库连接字符串
            SugarBase._connString = Configuration.GetSection("DB")["ExamDB"];
            services.AddDbContextPool<ExamDbContext>(options => options.UseMySQL(Configuration.GetSection("DB")["ExamDB"]));
            //注入Repository
            services.AddSingleton<IEventRepository, ExamEventRepository>();
            //注入Quartz
            services.UseQuartz(typeof(ExamEventJob));
            //注入MassTransit
            services.AddMassTransit(c =>
            {
                //声明消费者
                c.AddConsumer<ExamEventHandler>();
            });
            services.AddScoped<ExamEventHandler>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public static IBusControl BusControl { get; private set; }
        public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider, IHostingEnvironment env, IApplicationLifetime lifetime, IScheduler scheduler)
        {
            BusControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(new Uri(Configuration.GetSection("MQ")["Host"]), hst =>
                {
                    hst.Username(Configuration.GetSection("MQ")["UserName"]);
                    hst.Password(Configuration.GetSection("MQ")["Password"]);
                });
                // 重试
                cfg.UseRetry(ret =>
                {
                    ret.Interval(3, TimeSpan.FromSeconds(10));
                });
                cfg.ReceiveEndpoint(host, Configuration.GetSection("MQ")["Queue"], e =>
                {
                    e.LoadFrom(serviceProvider);
                });
            });
            //注入EventBus并开启
            lifetime.ApplicationStarted.Register(BusControl.Start);
            lifetime.ApplicationStarted.Register(BusControl.Stop);
            // 开启Quartz，30秒钟执行一次
            QuartzService.StartJob<ExamEventJob>(scheduler, TimeSpan.FromSeconds(30));
        }
    }
}
